package com.logos.cartoon.service.impl;

import com.google.gson.Gson;
import com.logos.cartoon.enums.AiModelEnum;
import com.logos.cartoon.req.ChatReq;
import com.logos.cartoon.resp.ChatResponse;
import com.logos.cartoon.service.DpService;
import com.logos.cartoon.utils.ChatReqUtil;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DpServiceImpl implements DpService {


    public static final String apiKey = "c137ee7b-cd87-4b15-8b51-7c5431729c2c";

    public static final String url = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";

    //    public static final String question = "你是谁";
    public static ConnectionPool connectionPool = new ConnectionPool(5, 1, TimeUnit.SECONDS);
    public static Dispatcher dispatcher = new Dispatcher();
    // The output time of the reasoning model is relatively long. Please increase the timeout period.
    public static ArkService service = ArkService.builder()
            .timeout(Duration.ofSeconds(1800))
            .connectTimeout(Duration.ofSeconds(20))
            .dispatcher(dispatcher)
            .connectionPool(connectionPool)
            .baseUrl(url)
            .apiKey(apiKey)
            .build();

    @Override
    public String chat(ChatReq chatReq) {
        final List<ChatMessage> streamMessages = new ArrayList<>();
        final ChatMessage streamUserMessage = ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(chatReq.getMessage())
                .build();
        streamMessages.add(streamUserMessage);

        ChatCompletionRequest streamChatCompletionRequest = ChatCompletionRequest.builder()
                .model(AiModelEnum.DEEP_SEEK.desc)
                .messages(streamMessages)
                .build();

        StringBuilder sbRet = new StringBuilder();
        try {
            service.streamChatCompletion(streamChatCompletionRequest)
                    .doOnError(Throwable::printStackTrace)
                    .blockingForEach(
                            delta -> {
                                if (!delta.getChoices().isEmpty()) {
                                    String content = (String) delta.getChoices().get(0).getMessage().getContent();
                                    if (StringUtils.isNotEmpty(content)) {
                                        // 清理多余换行符
                                        content = content.replaceAll("\\s+", " ").trim();
                                        sbRet.append(content);
                                    }
                                }
                            }
                    );
        } catch (Exception e) {
            e.printStackTrace();
            return "服务器繁忙,稍后再试";
        }
        // 最终返回前再次清理
        return sbRet.toString().replaceAll("\\s+", " ").trim();
    }


//    @Resource
//    public ChatReqUtil chatReqUtil;
//
//
//    public static final String deep_seek = "deepseek-r1:8b";
//
//    public static final String ailun = "Eren:latest";
//
//    @Override
//    public String chat(ChatReq chatReq) {
//        // 配置 OkHttp 客户端并设置超时时间
//        OkHttpClient client = new OkHttpClient.Builder()
//                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间为 60 秒
//                .writeTimeout(60, TimeUnit.SECONDS) // 设置写入超时时间为 60 秒
//                .connectTimeout(15, TimeUnit.SECONDS) // 设置连接超时时间为 15 秒
//                .build();
//
//        MediaType JSON = MediaType.get("application/json; charset=utf-8");
//        RequestBody body = RequestBody.create(chatReqUtil.createJson(deep_seek,chatReq.getMessage()), JSON);
//
//        Request request = new Request.Builder()
//                .url(ChatReqUtil.chatUrl)
//                .post(body)
//                .build();
//        String ret ="服务器繁忙,稍后再试";
//        try (Response response = client.newCall(request).execute()) {
//            if (response.isSuccessful()) {
//                System.out.println("Response Code : " + response.code());
//                String responseBody = response.body().string();
//                System.out.println("Response Body : " + responseBody);
//
//                // 解析响应字符串
//                Gson gson = new Gson();
//                ChatResponse chatResponse = gson.fromJson(responseBody, ChatResponse.class);
//
//                // 获取 message 中的 content
//                String messageContent = chatResponse.getMessage().getContent();
////                System.out.println("Full Message Content : " + messageContent);
//
//                // 使用正则表达式提取 </think> 标签后面的内容
//                ret = extractContentAfterThink(messageContent);
////                System.out.println("Message Content : " + thinkContent);
//            } else {
//                System.out.println("Request failed: " + response.code());
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return ret;
//    }
//
//    private static String extractContentAfterThink(String content) {
//        // 使用 DOTALL 模式以匹配多行字符串中的任意字符，包括换行符
//        Pattern pattern = Pattern.compile("</think>(.*)", Pattern.DOTALL);
//        Matcher matcher = pattern.matcher(content);
//        if (matcher.find()) {
//            String extractedContent = matcher.group(1).trim();
//            System.out.println("Extracted Content : " + extractedContent);
//            return extractedContent;
//        } else {
//            System.out.println("No match found for </think> tag.");
//            return "";
//        }
//    }

}
